package de.mmis.core.base.abstracttree.serializer.selector;

import java.util.Map;

import de.mmis.core.base.abstracttree.InnerNode;
import de.mmis.core.base.abstracttree.Tree;
import de.mmis.core.base.abstracttree.serializer.DeserializableException;
import de.mmis.core.base.abstracttree.serializer.SerializerHelper;
import de.mmis.core.base.gclass.GClass;

public class SequenceSelector extends InstanceSelector {

	private Tree[] subTrees;
	private ClassLoader classLoader;

	public SequenceSelector(Tree[] exps, ClassLoader classLoader, String id,
			Map<String, Object> idmap) {
		super(id, idmap);
		this.subTrees = exps;
		this.classLoader = classLoader;
	}

	@Override
	public Object createInstance(GClass gclass)
			throws InstanceSelectorException {
		Object ret = null;
		for (int i = 0; i < subTrees.length; i++) {
			try {
				ret = SerializerHelper.deserializeObject(
						subTrees[i],
						subTrees.length == i + 1 ? gclass : GClass
								.fromClass(Object.class), this.classLoader,
						getIDMap());
			} catch (DeserializableException e) {
				throw new InstanceSelectorException("sequence "
						+ new InnerNode(subTrees)
						+ " deserialization error in element " + i, e);
			}
		}
		return ret;
	}
}
